package com.nuoniu.sibanyun.service.erp.barcode.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.common.exception.NuoNiuException;
import com.nuoniu.sibanyun.entity.erp.barcode.ErpBarcodeRuleContent;
import com.nuoniu.sibanyun.entity.vo.ErpBarcodeRuleContentVo;
import com.nuoniu.sibanyun.mapper.erp.barcode.ErpBarcodeRuleContentMapper;
import com.nuoniu.sibanyun.service.erp.barcode.IErpBarcodeRuleContentService;
import com.nuoniu.sibanyun.userThread.UserInfo;
import com.nuoniu.sibanyun.userThread.UserThreadLocal;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 白强
 * @since 2021-11-08
 */
@Service
public class ErpBarcodeRuleContentServiceImpl extends ServiceImpl<ErpBarcodeRuleContentMapper, ErpBarcodeRuleContent> implements IErpBarcodeRuleContentService {

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public void saveRuleContent(List<ErpBarcodeRuleContent> ruleContentList,Long ruleId) {
        if(null == ruleContentList ||ruleContentList.size() ==  0)throw new NuoNiuException("适用对象不能为空");
        if(ruleContentList.stream().noneMatch(f->null != f.getIsCode() && f.getIsCode()))throw new NuoNiuException("请设置参与编码的属性内容");
        List<Long> collectIds = ruleContentList.stream().map(ErpBarcodeRuleContent::getId).collect(Collectors.toList());
        if(collectIds.size() > 0){
            //删除明细
            QueryWrapper<ErpBarcodeRuleContent> wrapper = new QueryWrapper();
            wrapper.eq("barcode_rule_id", ruleId);
            wrapper.notIn("id", collectIds);
            remove(wrapper);
        }
        saveOrUpdateBatch(ruleContentList);
    }

    @Override
    public List<ErpBarcodeRuleContent> listByRuleId(Long ruleId) {
        QueryWrapper<ErpBarcodeRuleContent> wrapper = new QueryWrapper();
        wrapper.eq("barcode_rule_id", ruleId);
        List<ErpBarcodeRuleContent> list = list(wrapper);
        return list;
    }

    @Override
    public List<ErpBarcodeRuleContentVo> listErpBarcodeRuleContentVo(Long ruleId,String voucherTypeCode) {
        UserInfo userInfo = UserThreadLocal.get();
        List<ErpBarcodeRuleContentVo> erpBarcodeRuleContentVos = baseMapper.listErpBarcodeRuleContentVo(ruleId,voucherTypeCode, userInfo.getCompanyId());
        return erpBarcodeRuleContentVos;
    }
}
